<template>
  <div class="page-container">
    <div class="store-info">
      <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
        <card class="add-info-card" title="基本信息">
          <page-form-row>
            <page-form-item field="industryName" label="同行名称" required>
              <i-input placeholder="请输入" v-model="form.industryName" :max-length="30" />
            </page-form-item>
            <page-form-item field="cityCode" label="省/市" required>
              <city-cascader v-model="form.cityCode" @change="changeCityFn" />
            </page-form-item>
            <page-form-item field="address" label="地址" required>
              <i-input placeholder="请选择" v-model="form.address" readonly @click="siteCoordinatesClickFn" />
              <icon-location :size="25" class="icon-location" @click="siteCoordinatesClickFn" />
            </page-form-item>
          </page-form-row>
        </card>
        <card class="add-info-card link-info" title="同行联系人">
          <div class="link-man-list">
            <div class="link-man-item">
              <page-form-row>
                <page-form-item field="contactName" label="姓名">
                  <i-input placeholder="请输入" v-model="form.contactName" :max-length="20" />
                </page-form-item>
                <page-form-item field="contactPhone" label="手机号">
                  <i-input placeholder="请输入" v-model="form.contactPhone" :max-length="11" />
                </page-form-item>
              </page-form-row>
            </div>
          </div>
        </card>
        <card class="add-info-card link-info" title="发票信息">
          <div class="link-man-list">
            <div class="link-man-item">
              <page-form-row>
                <page-form-item field="invoiceCompanyName" label="抬头">
                  <i-input placeholder="请输入" v-model="form.invoiceCompanyName" :max-length="30" />
                </page-form-item>
                <page-form-item field="invoiceType" label="发票类型">
                  <a-select v-model="form.invoiceType" placeholder="请选择" allow-clear>
                    <a-option v-for="item in peerPageData.invoiceTypeEnum" :key="item.value" :value="item.value" :label="item.label" />
                  </a-select>
                </page-form-item>
                <page-form-item field="invoiceNumber" label="纳税人识别号">
                  <i-input placeholder="请输入" v-model="form.invoiceNumber" :max-length="30" />
                </page-form-item>
                <page-form-item field="invoiceAddress" label="地址">
                  <i-input placeholder="请输入" v-model="form.invoiceAddress" :max-length="50" />
                </page-form-item>
                <page-form-item field="invoicePhone" label="电话">
                  <i-input placeholder="请输入" v-model="form.invoicePhone" :max-length="20" />
                </page-form-item>
              </page-form-row>
            </div>
          </div>
        </card>

        <!-- 银行账号 -->
        <BankAccount ref="bankAccountRef" :form="form" />

        <card class="add-info-card link-info" title="合同信息">
          <a-alert>
            <template #icon> <icon-exclamation-circle /> </template>支持
            .jpg、.jpeg、.png、.pdf、.doc、.docx格式，大小限制50M以内（仅支持上传一个附件）
          </a-alert>
          <div class="flex upload-wrapper">
            <drag-upload
              v-model="form.contractFileIdStr"
              :accept="['JPG', 'JPEG', 'PNG', 'PDF', 'DOC', 'DOCX']"
              :maxMB="50"
              class="mr-20px"
            />
            <div class="flex-1">
              <page-form-row>
                <page-form-item label="合同有效期" size="1/2">
                  <slot>
                    <i-range-picker v-model="form.dateRange" class="w-full" @change="(val: number[]) => changeDateFn(val)" />
                  </slot>
                </page-form-item>
              </page-form-row>
            </div>
          </div>
        </card>

        <card title="结算日配置" :showDivider="false">
          <a-alert class="alert-txt">
            <template #icon>
              <icon-exclamation-circle />
            </template>
            注意：当选择了30或31日为结算日时，对于没有30或31天的月份，将默认取对应月份的最后一天作为预警提醒。
          </a-alert>
          <div class="settlement-method">
            <page-form-item field="settlementPlan" label="结算方式">
              <a-radio-group class="method-radio" v-model="form.settlementPlan">
                <a-radio :value="item.value" v-for="item in peerPageData.settlementPlanEnum" :key="item.value">
                  {{ item.label }}
                  <a-tooltip :content="item.desc">
                    <icon-question-circle />
                  </a-tooltip>
                </a-radio>
              </a-radio-group>
            </page-form-item>
            <span class="day-box" v-if="form.settlementPlan && form.settlementPlan !== 10">
              <a-select style="width: 240px" placeholder="请选择" v-model="form.settlementDay" allow-clear>
                <a-option v-for="item in 31" :key="item" :value="item">
                  {{ item }}
                </a-option>
              </a-select>
              <span class="day-txt"> 日，进行结算</span>
            </span>
          </div>
        </card>
      </page-form>
    </div>
  </div>

  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />

  <!-- 坐标选择 -->
  <lnglat-picker-modal ref="lnglatPickerModalRef" @change="pointChangeFn" />
</template>

<script setup lang="ts" name="PeerForm">
  import { usePageDict } from '@/hooks/useDict'
  import { ref, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { isMobile } from '@/utils/validate'
  import { updatePeer, getPeerDetail } from '@/api/market/peer'
  import useNavigate from '@/hooks/useNavigate'
  import BankAccount from '@/views/market/components/bank-account.vue'

  const { navigateBack } = useNavigate()

  const tmpChangeCityOption = ref<any>({})
  const route = useRoute()
  const peerPageData = usePageDict('peerPageData')
  const formRef = ref()
  const form = ref<any>({
    settlementDay: 1,
    backInfoList: [],
  })
  const fileType = 'JPG、JPEG、PNG、PDF、DOC、DOCX'
  const lnglatPickerModalRef = ref()
  const validateFn = (value: string, cb: (msg?: string) => void) => {
    if (!value || value == '') {
      cb()
    } else {
      if (!isMobile(value)) {
        cb('手机号格式不正确')
      }
    }
  }

  const rules = ref({
    industryName: { required: true, message: '请输入同行名称', trigger: 'change' },
    cityCode: { required: true, message: '请选择省/市', trigger: 'change' },
    address: { required: true, message: '请选择地址', trigger: 'change' },
    contactName: { required: false, message: '请输入姓名' },
    contactPhone: { required: false, validator: validateFn },
    invoicePhone: { required: false, maxLength: 20 },
  })

  const changeCityFn = (value: string, option: any) => {
    if (tmpChangeCityOption.value && tmpChangeCityOption.value.cityCode == option.cityCode) {
      return
    }
    form.value.provinceCode = option.provinceCode
    form.value.cityCode = option.cityCode
    form.value.address = ''
    tmpChangeCityOption.value = option
  }

  const siteCoordinatesClickFn = () => {
    lnglatPickerModalRef.value.open().then((map: any) => {
      lnglatPickerModalRef.value.setCity(map, form.value.cityCode)
    })
  }

  const changeDateFn = (value: number[]) => {
    form.value.contractBeginDate = value[0]
    form.value.contractEndDate = value[1]
  }

  const pointChangeFn = (lnglat: number[], option: any) => {
    form.value.address = option.formattedAddress
    form.value.longitude = lnglat[0]
    form.value.latitude = lnglat[1]
    if (option) {
      const adcode = option.addressComponent.adcode
      form.value.address = option.formattedAddress
      form.value.provinceCode = String(parseInt((adcode / 10000) as unknown as string) * 10000)
      form.value.cityCode = String(parseInt((adcode / 100) as unknown as string) * 100)
      form.value.districtCode = adcode
      // fixme: 坐标选择无法返回省份 code，此时无法更新 form.provinceCode
      // 如果直接调接口目前也没问题 provinceCode 非必填，且后端会补 provinceCode 数据

      formRef.value.validateField(['cityCode', 'address'])
    }
  }

  const okLoading = ref(false)
  const bankAccountRef = ref()
  const submitFn = (noticeSuccess: () => void) => {
    formRef.value.validate(async (error: any) => {
      if (!error) {
        const validateRes = await bankAccountRef.value.validate()
        if (validateRes == false) return
        updatePeer(form.value)
          .then(() => {
            // 成功提示
            noticeSuccess()
            navigateBack()
          })
          .finally(() => {
            okLoading.value = false
            tmpChangeCityOption.value = {}
          })
      }
    })
  }

  const getInfoDetail = (id: string | string[]) => {
    getPeerDetail({ id }).then((res: any) => {
      const { result } = res
      result.dateRange = [result.contractBeginDate, result.contractEndDate]
      // 默认1日
      if (result.settlementDay === undefined) {
        result.settlementDay = 1
      }
      form.value = result
    })
  }

  onMounted(() => {
    const id = route.params.id
    if (id) {
      getInfoDetail(id)
    }
  })
</script>

<style scoped lang="less">
  :deep(.custom-divider) {
    margin-top: 0;
  }
  .upload-wrapper,
  .settlement-method {
    padding: 20px 0 0;
  }

  .upload-wrapper {
    margin-bottom: 20px;
  }

  .alert-txt {
    font-size: 12px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #1d2129;
    line-height: 22px;
  }

  .settlement-method {
    width: 438px;
    padding: 16px 16px;
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    border: 1px solid #e5e8ef;
    margin-top: 16px;
    box-sizing: border-box;

    .method-radio {
      display: flex;

      .arco-radio {
        width: max-content;
      }
    }

    .day-box {
      width: 372px;
      display: flex;
      background: rgba(247, 248, 250, 0.5);
      border-radius: 0px 0px 0px 0px;
      opacity: 1;
      box-sizing: border-box;
      padding: 16px;
      align-items: center;

      .day-txt {
        margin-left: 16px;
        white-space: nowrap;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #1d2129;
        line-height: 22px;
      }
    }
  }
  .mr-20px {
    margin-right: 20px;
  }

  .icon-location {
    display: inline-block;
    width: 25px;
    height: 32px;
    margin-left: 5px;
    cursor: pointer;
  }
</style>
